package com.hst.web.base.service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.core.json.JsonUtil;
import com.hst.web.auth.po.User;
import com.hst.web.base.entity.TAccountIdentity;
import com.hst.web.base.entity.TAccountInfo;
import com.hst.web.base.entity.TCompanyContractor;
import com.hst.web.base.entity.TCompanyEmployee;
import com.hst.web.base.entity.TContractorInfo;
import com.hst.web.base.ui.ContractorInfo;
import com.hst.web.base.ui.ContractorUpgrade;
import com.hst.web.common.utils.ConstantUtil;
import com.hst.web.sys.entity.TRole;
import com.hst.web.sys.entity.TUser;
import com.hst.web.sys.entity.TUserContractor;
import com.hst.web.sys.entity.TUserRole;
import com.hst.web.sys.service.UserService;

@Service
@Transactional
public class ContractorService {

	@Autowired
	IORDao dao;

	@Autowired
	UserRoleService us;
	
	@Autowired
	UserService userService;	

	/**
	 * 保存
	 * @param op
	 * @param data
	 * @param m
	 * @throws Exception 
	 */
	public void saveContractor(String op,String data,Model m) throws Exception {
		User u = (User) ServiceContext.getInstance().getUser();
		ContractorInfo con1 = JsonUtil.read(data, ContractorInfo.class);
		TContractorInfo contractor = JsonUtil.read(data, TContractorInfo.class);
		
		//检测本企业是否存在同名承包商
		String companyCode= u.getCompanyCode();
		String contractorAlisa = con1.getContractorAlisa();
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq, "companyCode", companyCode));
		querys.add(new ORQuery(Op.eq, "contractorAlisa", contractorAlisa));
		List<TCompanyContractor> companyContractorList = dao.list(TCompanyContractor.class, querys);
		if (companyContractorList.size() > 0) {
			throw new Exception("该企业下存在同名承包商");
		}
		
		TCompanyContractor rel = new TCompanyContractor();
		if("1".equals(op)) { //存在承包商 添加关联关系
			rel.setContractorCode(contractor.getContractorCode());
			rel.setCompanyCode(u.getCompanyCode());
			rel.setContractorAlisa(con1.getContractorAlisa());
			rel.setContractexpImg(con1.getContractexpImg());
			rel.setContractImg(con1.getContractImg());
			rel.setContractStampImg(con1.getContractStampImg());
			dao.save(rel);

			ContractorInfo con = new ContractorInfo();
			BeanUtils.copyProperties(con, contractor);
			con.setContractorAlisa(con1.getContractorAlisa());
			con.setContractexpImg(con1.getContractexpImg());
			con.setContractImg(con1.getContractImg());
			con.setContractStampImg(con1.getContractStampImg());
			m.addAttribute("con",JsonUtil.toString(con));
		} else { //不存在承包商 添加关联关系
			if(StringUtils.isEmpty(contractor.getContractorName())) {
				contractor.setContractorName(con1.getContractorAlisa());
			}
			contractor = dao.save(contractor);
			rel.setContractorCode(contractor.getContractorCode());
			rel.setCompanyCode(u.getCompanyCode());
			rel.setContractorAlisa(con1.getContractorAlisa());
			rel.setContractexpImg(con1.getContractexpImg());
			rel.setContractImg(con1.getContractImg());
			rel.setContractStampImg(con1.getContractStampImg());
			dao.save(rel);

			ContractorInfo con = new ContractorInfo();
			BeanUtils.copyProperties(con, contractor);
			con.setContractorAlisa(con1.getContractorAlisa());
			con.setContractexpImg(con1.getContractexpImg());
			con.setContractImg(con1.getContractImg());
			con.setContractStampImg(con1.getContractStampImg());
			m.addAttribute("con",JsonUtil.toString(con));
		}
	}

	public void delContract(List<ContractorInfo> contractors) {
		User u = (User) ServiceContext.getInstance().getUser();
		List<String> contractorCodes = new ArrayList<String>();
		for(ContractorInfo contractor:contractors) {
			contractorCodes.add(contractor.getContractorCode());
		}
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"companyCode",u.getCompanyCode()));
		querys.add(new ORQuery(Op.in,"contractorCode",contractorCodes));
		List<TCompanyContractor> rels = dao.list(TCompanyContractor.class,querys);
		for(TCompanyContractor rel:rels) {
			dao.delete(rel);
		}
	}

	/**
	 * 承包商管理员升级
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	public void contractorUpgrade(String data,String newRole,
			String passwd,String account,Model m) throws JsonParseException, JsonMappingException, IOException {
		User u = (User) ServiceContext.getInstance().getUser();
		ContractorUpgrade emp = JsonUtil.read(data, ContractorUpgrade.class);
		String employeeCode = emp.getEmployeeCode();		
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"employeeCode",emp.getEmployeeCode()));

		List<TUser> users = dao.list(TUser.class,querys);
		if(users.size() > 0) { //有账号
			TUser user = users.get(0);
			//根据角色修正UserTypeOld字段映射值
			user.setUserTypeOld(ConstantUtil.USETYPEMAP.get(newRole));
			dao.update(user);
			TRole role = us.userRole(user.getId());

			if(role != null && newRole.equals(role.getId())){ //是否是选择角色
//				if(account.equals(user.getOperatorNbr())
////						&& passwd.equals(user.getPassword())
//				)
//				{ //账号密码匹配添加所管承包商
					//查询是否有关联
					querys = new ArrayList<ORQuery>();
					querys.add(new ORQuery(Op.eq,"userid",user.getId()));
					querys.add(new ORQuery(Op.eq,"contractorCode",emp.getContractor()));
					querys.add(new ORQuery(Op.eq,"companyCode",u.getCompanyCode()));
					List<TUserContractor> rels = dao.list(TUserContractor.class,querys);
					if(rels.size() == 0) {
						TUserContractor rel = new TUserContractor();
						rel.setCompanyCode(u.getCompanyCode());
						rel.setContractorCode(emp.getContractor());
						rel.setUserid(user.getId());
						dao.save(rel);
					}
					
					//同步更新TAccountInfo表的useType字段
					String userName = vaildateAccountIdentity(employeeCode);
					if (StringUtils.isNotEmpty(userName)) {
						TAccountInfo accountInfo = dao.get(TAccountInfo.class, userName);
						if (accountInfo != null) {
							accountInfo.setUseType(ConstantUtil.USETYPEMAP.get(newRole));
							dao.update(accountInfo);
						}
					}
					m.addAttribute("success","success");
//				}
//				else {
//					m.addAttribute("errorCode","error");
//					m.addAttribute("msg","账号密码不匹配");
//				}
			}else {  //不是所选角色
//				if(account.equals(user.getOperatorNbr())
////						&& passwd.equals(user.getPassword())
//				) { //账号密码匹配添加所管承包商
					querys = new ArrayList<ORQuery>();
					querys.add(new ORQuery(Op.eq, "userid", user.getId()));
					List<TUserRole> rels = dao.list(TUserRole.class, querys);
					for(TUserRole rel:rels) {
						dao.delete(rel);
					}
					TUserRole rel = new TUserRole();
					rel.setRoleid(newRole);
					rel.setUserid(user.getId());
					dao.save(rel);

					//查询是否有关联
					querys = new ArrayList<ORQuery>();

					querys.add(new ORQuery(Op.eq,"userid",user.getId()));
					querys.add(new ORQuery(Op.eq,"contractorCode",emp.getContractor()));
					querys.add(new ORQuery(Op.eq,"companyCode",u.getCompanyCode()));
					List<TUserContractor> rels1 = dao.list(TUserContractor.class,querys);
					if(rels1.size() == 0) {
						TUserContractor rel1 = new TUserContractor();
						rel1.setCompanyCode(u.getCompanyCode());
						rel1.setContractorCode(emp.getContractor());
						rel1.setUserid(user.getId());
						dao.save(rel1);
					}

					user.setUserType("1"); //修改账号类型为承包商
					dao.update(user);
					
					//同步更新TAccountInfo表的useType字段
					String userName = vaildateAccountIdentity(employeeCode);
					if (StringUtils.isNotEmpty(userName)) {
						TAccountInfo accountInfo = dao.get(TAccountInfo.class, userName);
						if (accountInfo != null) {
							accountInfo.setUseType(ConstantUtil.USETYPEMAP.get(newRole));
							dao.update(accountInfo);
						}
					}
					
					m.addAttribute("success","success");
//				}else {
//					m.addAttribute("errorCode","error");
//					m.addAttribute("msg","账号密码不匹配");
//				}
			}
		}else {
			// 没有账号
			//判断是否有实名认证信息
			String userName = vaildateAccountIdentity(emp.getEmployeeCode());
			if(StringUtils.isNotEmpty(userName)) { //实名认证通过
				TAccountInfo account1 = dao.get(TAccountInfo.class, userName);
				if(account1 != null) {
//					if(account1.getUserName().equals(account) && account1.getPassword().equals(passwd)) {
						//通过实名认证账号添加系统账号
						TUser newUser = new TUser();
						newUser.setPassword(account1.getPassword());
						newUser.setOperatorNbr(account1.getUserName());
						newUser.setEmployeeCode(emp.getEmployeeCode());
						newUser.setLoginName(emp.getFullname());
						newUser.setValidflag("1");  //是否有效
						newUser.setUserType("1"); //用户类型承包商用户
						//根据角色修正UserTypeOld字段映射值
						newUser.setUserTypeOld(ConstantUtil.USETYPEMAP.get(newRole));
						newUser = dao.save(newUser);

						TUserRole rel = new TUserRole(); //添加用户角色
						rel.setRoleid(newRole); // 承包商管理员
						rel.setUserid(newUser.getId());
						dao.save(rel);

						TUserContractor rel1 = new TUserContractor();
						rel1.setCompanyCode(u.getCompanyCode());
						rel1.setContractorCode(emp.getContractor());
						rel1.setUserid(newUser.getId());
						dao.save(rel1);
						
						//同步更新TAccountInfo表的useType字段
						account1.setUseType(ConstantUtil.USETYPEMAP.get(newRole));
						dao.update(account1);						
						
						m.addAttribute("success", "success");
//					}else {
//						m.addAttribute("errorCode","error");
//						m.addAttribute("msg","账号密码不匹配");
//					}
				}else {
					m.addAttribute("errorCode","error");
					m.addAttribute("msg","未实名认证的人员不能赋职");
				}
			}else { //实名认证失败
				m.addAttribute("errorCode","error");
				m.addAttribute("msg","未实名认证的人员不能赋职");
			}
		}
	}

	/**
	 * 校验是否实名认证
	 */
	private String vaildateAccountIdentity(String employeeCode) {
		TCompanyEmployee employee = dao.get(TCompanyEmployee.class, employeeCode);
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"papersNumber",employee.getPapersNumber()));
		querys.add(new ORQuery(Op.eq,"papersType",employee.getPapersType()));
		//querys.add(new ORQuery(Op.eq,"fullname",employee.getFullname()));
		List<TAccountIdentity> identities = dao.list(TAccountIdentity.class,querys);
		if(identities.size() > 0) {
			return identities.get(0).getUserName();
		}else {
			return null;
		}
	}

	/**
	 * 撤职
	 * @return
	 */
	public void delgrade(ContractorUpgrade upgrade,Model m) {
		User u = (User) ServiceContext.getInstance().getUser();
		String employeeCode = upgrade.getEmployeeCode();
		List<ORQuery> querys = new ArrayList<ORQuery>();
		querys.add(new ORQuery(Op.eq,"employeeCode",employeeCode));
		List<TUser> users = dao.list(TUser.class,querys);
		if(users.size() > 0) {
			TUser user = users.get(0);
			querys = new ArrayList<ORQuery>();
			querys.add(new ORQuery(Op.eq,"userid",user.getId()));
			querys.add(new ORQuery(Op.eq,"companyCode",u.getCompanyCode()));
			querys.add(new ORQuery(Op.eq,"contractorCode",upgrade.getContractor()));
			List<TUserContractor> reList = dao.list(TUserContractor.class,querys);
			for(TUserContractor rel:reList) {
				dao.delete(rel);
			}

			querys = new ArrayList<ORQuery>();
			querys.add(new ORQuery(Op.eq,"userid",user.getId()));
			reList = dao.list(TUserContractor.class,querys);
			if(reList.size() == 0) {  // 是否还有其他的承包商管理员身份
				List<TUserRole> rels = dao.list(TUserRole.class,querys);
				for(TUserRole rel:rels) {
					dao.delete(rel);
				}  // 没有就删除角色
			}
			
			//同步更新TAccountInfo表的useType字段
			String userName = userService.vaildateAccountIdentity(employeeCode);
			if (StringUtils.isNotEmpty(userName)) {
				TAccountInfo accountInfo = dao.get(TAccountInfo.class, userName);
				if (accountInfo != null) {
					accountInfo.setUseType(ConstantUtil.USETYPEMAP.get("personal"));
					dao.update(accountInfo);
				}
			}
			
			m.addAttribute("success","success");
		}
	}
}
